import { useState, useEffect } from "react";
import { Table, Button, Tooltip, Modal, Badge, message } from "antd";
import { useNavigate, Link, useLocation } from "react-router-dom";
import {
	DeleteOutlined,
	FileSearchOutlined,
	ExclamationCircleOutlined,
} from "@ant-design/icons";
import { getDataList, deleteTask } from "@/api/url";
import Layout from "./Layout";
import { apply_sceneMap } from "./utils/statusMap";
import styles from "./taskList.module.scss";

function TaskList() {
	const [dataList, setataList] = useState(0);
	const [pageInfo, setPageInfo] = useState({ page: 1, pagesize: 15 });
	const [loading, setLoading] = useState(false);
	const [total, setTotal] = useState(0);
	const navigate = useNavigate();

	// // 获取重定向的参数
	// const location = useLocation();
	// // 获取查询参数字符串
	// const search = location.search;
	// // 解析查询参数
	// const queryParams = new URLSearchParams(search);
	// // 获取特定的查询参数
	// const token = queryParams.get("token");
	// const sys = queryParams.get("sys");
	// console.log(token, sys);

	const getList = () => {
		getDataList(pageInfo)
			.then((res) => {
				const { data } = res;
				setataList(data?.data);
				setTotal(data.total);
			})
			.catch((err) => console.log(err))
			.finally(() => setLoading(false));
	};

	useEffect(() => {
		setLoading(true);
		getList();
	}, [pageInfo]);

	const statusMap = {
		0: ["default", "排队中"],
		1: ["processing", "加固中"],
		2: ["success", "加固成功"],
		3: ["error", "加固失败"],
	};

	const columns = [
		{
			title: "任务名称",
			dataIndex: "name",
			ellipsis: true,
			width: "20%",
			render: (text, record) => (
				<Link className="d-b ellipsis" to={`  `}>
					{text}
				</Link>
			),
		},
		{
			title: "状态",
			dataIndex: "task_status",
			render: (text) => (
				<Badge
					status={statusMap[text] && statusMap[text][0]}
					text={statusMap[text] && statusMap[text][1]}
				/>
			),
			sorter: (a, b) => a.task_status - b.task_status,
		},
		{
			title: "应用场景",
			dataIndex: "apply_scene",
			ellipsis: true,
			render: (text) => <span>{apply_sceneMap[text] || "- -"}</span>,
		},
		{
			title: "创建时间",
			dataIndex: "create_time",
			ellipsis: true,
			render: (text) => <span>{text || "- -"}</span>,
			// defaultSortOrder: 'descend',
			sorter: (a, b) => {
				let dateA = new Date(a.create_time).getTime();
				let dateB = new Date(b.create_time).getTime();
				return dateA - dateB;
			},
		},
		{
			title: "完成时间",
			dataIndex: "completion_time",
			ellipsis: true,
			render: (text) => <span>{text || "- -"}</span>,
			sorter: (a, b) => {
				let dateA = new Date(a.create_time).getTime();
				let dateB = new Date(b.create_time).getTime();
				return dateA - dateB;
			},
		},
		//查看 ；若当前任务状态 非测评完成，则展示为：
		//该任务状态为 测评完成 时可进行查看报告的操作，其余状态不可选；
		{
			dataIndex: "operate",
			title: "操作",
			width: 90,
			render: (text, record) => {
				const renderOperate1 = () => {
					if (record.task_status === 2) {
						return (
							<Tooltip title="查看加固报告">
								<FileSearchOutlined
									className="styleA"
									onClick={() =>
										navigate("/taskDetail", { state: { id: `${record.id}` } })
									}
								/>
							</Tooltip>
						);
					}
					return (
						<FileSearchOutlined style={{ cursor: "no-drop", color: "#888" }} />
					);
				};
				const renderDelete = () => {
					// 【测评中】【排队中】时该按钮置灰不允许点选
					// 2===(3||2) false
					if ([2, 3].includes(record.task_status)) {
						return (
							<Tooltip title="删除" key="del">
								<DeleteOutlined
									className="styleA"
									onClick={() => {
										Modal.confirm({
											okText: "删除",
											okType: "danger",
											cancelButtonProps: { type: "primary" },
											title: "确定删除吗？",
											icon: <ExclamationCircleOutlined />,
											content: "测评任务删除后不可恢复",
											onOk: () => {
												return deleteTask({ id: record.id }).then((result) => {
													if (result.error_code === 0) {
														setLoading(true);
														message.success("删除成功");
														getList();
													}
												});
											},
											onCancel() {
												console.log("Cancel");
											},
										});
									}}
								/>
							</Tooltip>
						);
					}
					return (
						<DeleteOutlined
							title="删除"
							style={{ cursor: "no-drop", color: "#888" }}
							key="del"
						/>
					);
				};
				return [
					<span style={{ marginRight: 16 }} key="opt">
						{renderOperate1()}
					</span>,
					renderDelete(),
				];
			},
		},
	];

	return (
		<Layout>
			<div className={styles.title}>
				<span className={styles.tableTitle}>任务列表</span>
				<Button
					style={{ marginBottom: 21, width: 116 }}
					type="primary"
					onClick={() => navigate("/evaluationTask")}
					key="outer"
				>
					新建加固任务
				</Button>
			</div>

			<Table
				columns={columns}
				dataSource={dataList}
				rowKey="id"
				pagination={{
					// ...pageInfo,
					current: pageInfo.page,
					pageSize: pageInfo.pagesize,
					showQuickJumper: true,
					showSizeChanger: false,
					total: total,
					showTotal: () => (
						<div
							style={{ position: "absolute", left: 0 }}
						>{`共 ${total} 条`}</div>
					),
					onChange: (page, pageSize) => {
						return setPageInfo({ page, pagesize: pageSize });
					},
				}}
				loading={loading}
				className={
					dataList?.length ? "" : "ant-table-placeholder-border-bottom-none"
				}
			/>
		</Layout>
	);
}

export default TaskList;
